<template>
  <!-- 发布任务页 -->
  <div class="box">
    <van-cell-group>
      <van-field
        disabled
        label="对应事件"
        placeholder="请选择事件"
        v-model="event"
        is-link
        @click="Choice = true"
      >
      </van-field>
      <van-popup
        v-model="Choice"
        round
        :safe-area-inset-bottom="true"
        :style="{ width:'80%' }"
        :overlay-style="{background:'rgba(0, 0, 0, 0.34)'}"
      >
        <div style="margin:30px">
          <van-radio-group
            v-model="radio"
            v-for="(item,i) in list"
            :key="i"
          >
            <van-radio
              :name='i'
              style="padding:5px;"
              @click="show_title_event(item.name)"
            >{{item.name}}</van-radio>
          </van-radio-group>
        </div>
      </van-popup>
    </van-cell-group>
    <van-cell-group>
      <van-field
        v-model="taskTitle"
        clearable
        label="任务标题"
        placeholder="任务标题"
      />
    </van-cell-group>
    <div
      class="public"
      @click="type = true"
    > <div class="left_wrap">
       <span
       class="Left"
      >任务类型</span>
    </div>
    <div class="right_wrap">
      <span
      class="Right"
      >{{isRecruit}}</span>
    </div>
     <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
      <!-- <van-icon
        name="arrow"
        :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
      /> -->
    </div>
    <van-popup
      v-model="type"
      round
      :safe-area-inset-bottom="true"
      :style="{width:'68%' }"
      :overlay-style="{background:'rgba(0, 0, 0, 0.34)'}"
    >
      <div style="margin:15px 20px;">
        <van-radio-group v-model="radio">
          <van-radio
            :style="{borderBottom:'0px',padding:'5px'}"
            :name="0"
            @click="show_isRecruit_id(0)"
          >招募</van-radio>
          <van-radio
            :style="{borderBottom:'0px',padding:'5px',marginTop:'5px'}"
            :name="1"
            @click="show_isRecruit_id(1)"
          >指派</van-radio>
          <van-radio
            :style="{borderBottom:'0px',padding:'5px',marginTop:'5px'}"
            :name="2"
            @click="show_isRecruit_id(2)"
          >多人</van-radio>
        </van-radio-group>
      </div>

    </van-popup>
    <van-cell-group>
      <van-field
        v-model="message"
        rows="5"
        :style="{borderTop:'1px solid silver',borderBottom:'1px solid silver'}"
        label="事件描述"
        type="textarea"
        placeholder="请输入事件描述"
        show-word-limit
      />
    </van-cell-group>
    <div
      class="public"
      v-show='release_scope'
      @click="show_Release_All"
    > 
      <div class="left_wrap">
        <span
        class="Left"
      >发布范围</span>
      </div>
      <div class="right_wrap">
        <span
        class="Right"
      >{{show_all}}</span>
      </div>
      <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
      <!-- <van-icon
        name="arrow"
        :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
      /> -->
    </div>
    <div
      class="public"
      v-show='release_scope'
      @click="show_time_one(1)"
    > 
      <div class="left_wrap" style="width:106px">
        <span
        class="Left"
      >领取截止时间</span>
      </div>
      <div class="right_wrap" style="margin-left:12px">
         <span
        class="Right"
      >{{get_time}}</span>
      </div>
      <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
      <!-- <van-icon
        name="arrow"
        :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
      /> -->
    </div>
    <div
      class="public"
      @click="show_time_two(2)"
    > 
      <div class="left_wrap">
        <span
        class="Left"
      >开始时间</span>
      </div>
      <div class="right_wrap">
        <span
        class="Right"
      >{{get_time_start}}</span>
      </div>
      
      <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
      <!-- <van-icon
        name="arrow"
        :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
      /> -->
    </div>
    <div
      class="public"
      @click="show_time_three(3)"
    > 
      <div class="left_wrap">
        <span
        class="Left"
      >结束时间</span>
      </div>
      <div class="right_wrap">
         <span
        class="Right"
      >{{get_time_end}}</span>
      </div>
      <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
      <!-- <van-icon
        name="arrow"
        :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
      /> -->
    </div>
    <!-- 时间插件 -->
    <van-popup
      v-model="time_one"
      :safe-area-inset-bottom="true"
      :style="{width:'86%',fontSize:'14px',borderRadius:'10px'}"
      :overlay-style="{background:'rgba(0, 0, 0, 0.34)'}"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        @confirm="getTime_one"
        @cancel="time_one=false"
      />

    </van-popup>
    <!-- 指派人员 -->
    <div
      class="public"
      v-show="assign"
      @click="show_depart_list_assign"
    > 
      <div class="left_wrap">
        <span
        class="Left"
      >指派人员</span>
      </div>
      <div class="right_wrap"> 
        <span
        class="Right"
      >{{assign_name}}</span>
      </div>
      <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
      <!-- <van-icon
        name="arrow"
        :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
      /> -->
    </div>
    <van-cell-group v-show="showMore">
      <van-field
        v-model="receiveNumber"
        type="digit"
        label="领取人数"
        placeholder="0"
      />
    </van-cell-group>
    <!-- 审核人 -->
    <div
      class="public"
      @click="showPersonnel_start"
    >
      <div class="left_wrap">
        <span
        class="Left"
      >审核人</span>
      </div>
      <div class="right_wrap">
        <span
        class="Right"
      >{{start_name}}</span>
      </div>
      <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
      <!-- <van-icon
        name="arrow"
        :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
      /> -->
    </div>
    <!-- 验收人 -->
    <div
      class="public"
      @click="show_department_end"
    > 
      <div class="left_wrap">
        <span
        class="Left"
      >验收人</span>
      </div>
      <div class="right_wrap">
        <span
        class="Right"
      >{{end_name}}</span>
      </div>
      <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
      <!-- <van-icon
        name="arrow"
        :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
      /> -->
    </div>
    <van-cell-group v-if="ISC == 1">
      <van-field
        disabled
        center
        clearable
        :label="C_name+'开启'"
      >
        <van-switch
          slot="button"
          size="24px"
          active-color="#3C9BFB"
          v-model="checked"
          @change="show_C"
        />
      </van-field>
    </van-cell-group>
    <van-cell-group>
      <van-field
        disabled
        center
        clearable
        label="上传图片"
      >
        <van-uploader
          v-model="fileLists"
          accept="image/png, image/jpeg,image/jpg"
          slot="input"
          multiple
          deletable
          :max-count="2"
          :before-read="before_Read"
          :after-read="afterRead"
          :before-delete='befor_Delete'
        />
      </van-field>
    </van-cell-group>
    <van-cell-group>
      <van-field
        disabled
        center
        clearable
        label="上传附件"
      >
        <van-uploader
          v-model="fileList"
          slot="input"
          :max-count="1"
          deletable
          accept=".doc,.pdf.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
          :after-read="after_read"
          :before-read="beforeRead"
          :before-delete='beforDelete'
        />
      </van-field>
    </van-cell-group>
    <van-cell-group
      v-show='release_scope'
      class="active"
      :style="{marginTop:'10px',position:'relative'}"
    >
      <van-field
        type="digit"
        v-model="receive"
        label="领取得分"
        :placeholder="'领取'+D_name"
      />
      <span
        v-show="checked"
        class="receive_C"
      ><input
          v-model="receiveScoreC"
          type="number"
          pattern="[0-9]*"
          style="border:none;width:100%"
          :placeholder="'领取'+C_name"
        ></span>
    </van-cell-group>
    <div v-show="show">
      <van-cell-group :style="{position:'relative'}">
        <van-field
          type="digit"
          v-model="complete"
          label="完成得分"
          :placeholder="'完成'+D_name"
        />
        <span
          class="receive_C"
          v-show="checked"
        ><input
            v-model="finishScoringC"
            type="number"
            pattern="[0-9]*"
            style="border:none;width:100%"
            :placeholder="'完成'+C_name"
          ></span>
      </van-cell-group>
      <van-cell-group :style="{position:'relative'}">
        <van-field
          type="digit"
          v-model="deduction"
          label="逾期扣分"
          :placeholder="'扣除'+D_name"
        />
        <span
          v-show="checked"
          class="receive_C"
        ><input
            type="number"
            pattern="[0-9]*"
            v-model="overdueScoreC"
            style="border:none;width:100%"
            :placeholder="'扣除'+C_name"
          ></span>
      </van-cell-group>
      <van-cell-group :style="{position:'relative'}">
        <van-field
          type="digit"
          v-model="beOverdue"
          label="逾期上限"
          placeholder="逾期上限天数"
        />
      </van-cell-group>
    </div>
    <!-- 子任务时间插件 -->
    <van-popup
      v-model="show_children_time"
      :safe-area-inset-bottom="true"
      :style="{width:'86%',fontSize:'14px',borderRadius:'10px'}"
      :overlay-style="{background:'rgba(0, 0, 0, 0.34)'}"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        @confirm="children_time_one"
        @cancel="show_children_time=false"
      />
    </van-popup>
    <!-- 开启子任务 -->
    <div
      v-show="it.isShow"
      style="margin-top:10px"
      v-for="(it,p) in children_list"
      :key="p+1"
    >
      <van-cell-group class="childer_list">
        <van-field
          v-model="it.taskTile"
          :label="'子任务'+ ++p"
          placeholder="任务标题"
        />
        <span style="position: absolute;right: 17px;top: 17px;" @click="receiveShow(it,p)">
          <van-icon name="clear" /></span>
      </van-cell-group>
      <van-cell-group :style="{position:'relative'}">
        <van-field
          type="digit"
          v-model="it.finishScoringD"
          label="完成得分"
          :placeholder="'完成'+D_name"
        />
        <span
          v-show="checked"
          class="receive_C"
        ><input
            v-model="it.finishScoringC"
            type="number"
            pattern="[0-9]*"
            style="border:none;width:100%"
            :placeholder="'完成'+C_name"
          ></span>
      </van-cell-group>
      <van-cell-group :style="{position:'relative'}">
        <van-field
          type="digit"
          v-model="it.overdueScoreD"
          label="逾期扣分"
          :placeholder="'扣除'+D_name"
        />
        <span
          v-show="checked"
          class="receive_C"
        ><input
            v-model="it.overdueScoreC"
            type="number"
            pattern="[0-9]*"
            style="border:none;width:100%"
            :placeholder="'扣除'+C_name"
          ></span>
      </van-cell-group>
      <van-cell-group>
        <van-field
          type="digit"
          v-model="it.overdueDays"
          label="逾期上限"
          placeholder="逾期上限天数"
        />
      </van-cell-group>
      <div
        class="public"
        @click="timeShow_start(it,p)"
      >
        <div class="left_wrap">
          <span
          class="Left"
        >开始时间</span>
        </div>
        <div class="right_wrap">
          <span
          class="Right"
        >{{it.startTime}}</span>
        </div>
        <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
        <!-- <van-icon
          name="arrow"
          :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
        /> -->
      </div>
      <div
        class="public"
        @click="timeShow_end(it,p)"
      >
        <div class="left_wrap">
          <span
        class="Left"
        >结束时间</span>
        </div>
        <div class="right_wrap">
          <span
          class="Right"
        >{{it.endTime}}</span>
        </div>
        <i class="van-icon van-icon-arrow van-cell__right-icon " ><!----></i>
        <!-- <van-icon
          name="arrow"
          :style="{float:'right',marginRight:'5vw',fontSize:'17px',lineHeight:'7vh',color:'#969799'}"
        /> -->
      </div>
    </div>

    <div
      class="public"
      v-show="Children_start"
    >
      <div class="left_wrap">
        <span
        class="Left"
      >开启子任务</span>
      </div>
      <div class="right_wrap">
        <span
        class="Right"
        @click="showChlid"
      >添加子任务</span>
      </div>
      
    </div>
    <van-button
      round
      :style="{width:'95%',height:'5.5vh',lineHeight:'5.5vh',marginTop:'10px'}"
      color="#3C9BFB"
      @click="show_sub"
    >提交</van-button>
     <van-overlay
      :show="isShowloading"
      @click="isShowloading = false"
    >
      <div
        class="wrapper"
        @click.stop
      >
        <van-loading
          vertical
          type="spinner"
          size="50"
        >附件上传中...</van-loading>
      </div>
    </van-overlay>
  </div>
</template>

<script type="text/javascript">
import {
  Cell,
  CellGroup,
  Field,
  Switch,
  Button,
  Icon,
  Popup,
  RadioGroup,
  Radio,
  Uploader,
  Search,
  Checkbox,
  CheckboxGroup,
  DatetimePicker,
  Toast,
  Overlay,
  Loading
} from "vant";
import personnel from "@/components/personnel";
import depart from "@/components/departmentList";
import axios from "axios";
export default {
  data() {
    return {
      isShowloading: false,
      showMore: false,
      show_children_time: false,
      depart_list_assign: false,
      depart_personnel_user: false,
      fileLists:[],
      fileList: [],
      list_checked: false,
      result: [],
      value: "",
      event: "",
      receive: "",
      message: "",
      beOverdue: "",
      deduction: "",
      complete: "",
      taskTitle: "",
      receiveNumber: "",
      isClick: true,
      release_scope: true,
      Children_start: true,
      assign: false,
      people: true,
      people_p: true,
      people_s: true,
      checked: false,
      isActive: false,
      show: true,
      get_time: "",
      get_time_start: "",
      get_time_end: "",
      Choice: false,
      radio: 0,
      type: false,
      list: [],
      userlist: [],
      userArr: [],
      depart: [],
      depart_list: [],
      userArr_list: [],
      depart_obj: {},
      time_one: false,
      value_people_one: "",
      isRecruit: "招募",
      start_name: "审核人",
      end_name: "验收人",
      assign_name: "指派人员",
      isRecruit_id: 0,
      start_id: 0,
      end_id: 0,
      minDate: new Date(2018, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      num_time: 1,
      is_c: 0,
      children_id: 0,
      show_Release: false,
      children_list: [],
      receiveScoreC: "",
      finishScoringC: "",
      overdueScoreC: "",
      public_time_start: 0,
      public_time_end: 0,
      time_isshow: 1,
      isSubTask: 0,
      index: 0,
      show_all: "默认全部",
      show_str: "",
      checkedNames: [],
      Total_num: 0,
      arr: [],
      isCheckAll: false,
      item_list: [],
      C_name: "",
      D_name: "",
      accepted_list: [],
      accepted_user: [],
      appointees_str: "",
      fileName: [],
      base64_url: [],
      sub_num: 0,
      open_num: 0,
      ISC:'',
      file_num: [],
      file_nums:[],
      filesNums:[]

    };
  },
  components: {
    depart,
    personnel,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Switch.name]: Switch,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Uploader.name]: Uploader,
    [Search.name]: Search,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [DatetimePicker.name]: DatetimePicker,
    [Loading.name]: Loading,
    [Overlay.name]: Overlay
  },
  created() {
    this.C_name = localStorage.getItem("c_name");
    this.D_name = localStorage.getItem("d_name");
    this.show_jsapi();
    this.getEvent();
    this.oneMoreTime();
    this.getIsC();
    this.event = localStorage.getItem("eventname");
    dd.biz.navigation.setTitle({
      title: "任务大厅" //控制标题文本，空字符串表示显示默认文本
    });
    this.get_time = this.getDay(1);
    this.get_time_start = this.getDay(0);
    this.get_time_end = this.getDay(2);
  },
  methods: {
    /**
     * rfj
     *
     */
     //C分开关
    async getIsC(){
      let corpId = localStorage.getItem("custid");
      const res = await this.$http.get(
        `yuepoints/getIsC?corpId=${corpId}`
      );
      // localStorage.setItem("ISC", res.data.data.is_c_code);
      this.ISC = res.data.data.is_c_code
    },
    // 钉钉鉴权
    async show_jsapi() {
      let corpId = localStorage.getItem("custid");
      // let corpId = this.$utils.getUrlKey("custid");
      let url = location.href.split("#")[0];
      const res = await this.$http.get(
        `dingapi/getJsapiConfig?corpId=${corpId}&url=${url}`
      );
      let config = res.data.data;
      localStorage.setItem("appId", config.agentId);
      dd.config({
        agentId: config.agentId,
        corpId: config.corpId,
        timeStamp: config.timeStamp,
        nonceStr: config.nonceStr,
        signature: config.signature,
        jsApiList: [
          "runtime.info",
          "biz.ding.post",
          "biz.ding.create",
          "biz.chat.pickConversation",
          "device.notification.prompt",
          "device.notification.confirm",
          "device.notification.alert",
          "biz.navigation.setRight",
          "biz.chat.open",
          "biz.util.open",
          'biz.util.openLink',
          "biz.user.get",
          "biz.contact.choose",
          "biz.telephone.call",
          "biz.util.uploadImage",
          // "device.accelerometer.watchShake",
          // "biz.map.locate",
          // "device.geolocation.get",
          "biz.customContact.choose",
          "biz.contact.complexPicker",
          "biz.contact.departmentsPicker",
        ]
      });
    },
    // 再来一次
    async oneMoreTime() {
      // console.log(this.$route.query.type);
      let item = this.$route.query.type;
      if (item == 6 && item != undefined) {
        let id = this.$route.query.id;
        let userId = localStorage.getItem("userId");
        let corpId = localStorage.getItem("custid");
        const res = await this.$http.get(
          `yuepoints/task/again?corpId=${corpId}&userId=${userId}&id=${id}`
        );
        const { data, errcode } = res.data;
        if (errcode == "0000") {
          // 事件名称
          this.event = data.event_name;
          // 任务标题
          this.taskTitle = data.task_title;
          // 发布范围
          let depart_str = "";
          if (data.scope[0] == 0) {
            this.show_all = "默认全部";
            // this.show_str = 0;
          } else {
            this.show_all = "已选择" + data.scope.length + "个部门";
            for (let i = 0; i < data.scope.length; i++) {
              depart_str += `${data.scope[i]},`;
            }
            this.show_str = depart_str;
          }
          // 任务类型
          this.isRecruit_id = data.is_recruit;
          if (data.is_recruit == 0) {
            // 领取得分
            this.receive = data.receive_code_d;
            this.receiveScoreC = data.receive_code_c;
            this.showMore = false;
            this.isRecruit = "招募";
            this.release_scope = true;
            this.Children_start = true;
            this.assign = false;
          }
          let userList_string = "";
          if (data.is_recruit == 1) {
            this.receive = "";
            this.receiveScoreC = "";
            this.isRecruit = "指派";
            this.showMore = false;
            this.release_scope = false;
            this.Children_start = false;
            this.assign = true;
            this.assign_name =
              data.task_user[0].user_name + "等" + data.task_user.length + "人";
            for (let f = 0; f < data.task_user.length; f++) {
              userList_string += `${data.task_user[f].user_id},`;
            }
            this.appointees_str = userList_string;
          }
          if (data.is_recruit == 2) {
            // 领取得分
            this.receive = data.receive_code_d;
            this.receiveScoreC = data.receive_code_c;
            this.isRecruit = "多人";
            this.showMore = true;
            this.release_scope = true;
            this.Children_start = false;
            this.assign = false;
            // 领取人数
            this.receiveNumber = data.receive_number;
          }
          // 任务描述
          this.message = data.task_desc;
          // 审核人
          this.start_id = data.approval_user_id;
          this.start_name = data.approval_name;
          // 验收人
          this.end_id = data.check_user_id;
          this.end_name = data.check_name;
          // 是否包含子任务
          this.isSubTask = data.haveSecondary;
          if (data.haveSecondary == 1) {
            for (let j = 0; j < data.secondary.length; j++) {
              this.children_list.push({
                taskTile: data.secondary[j].task_title,
                startTime: this.get_time,
                endTime: this.get_time_end,
                finishScoringD: data.secondary[j].complete_code_d,
                finishScoringC: data.secondary[j].complete_code_c,
                overdueScoreD: data.secondary[j].overtime_code_d,
                overdueScoreC: data.secondary[j].overtime_code_c,
                overdueDays: data.secondary[j].overtime_end_day,
                isShow: true
              });
            }
          }
          // C分是否开启
          if (data.is_codeC == 1) {
            this.checked = true;
            this.is_c = 1;

            if (data.haveSecondary == 0) {
              this.complete = data.complete_code_d;
              this.deduction = data.overtime_code_d;
              this.beOverdue = data.overtime_end_day;
              this.finishScoringC = data.complete_code_c;
              this.overdueScoreC = data.overtime_code_c;
            } else {
              this.show = false;
            }
          } else {
            this.checked = false;
            this.is_c = 0;

            if (data.haveSecondary == 0) {
              this.complete = data.complete_code_d;
              this.deduction = data.overtime_code_d;
              this.beOverdue = data.overtime_end_day;
            } else {
              this.show = false;
            }
          }
          // let imgUrl = "";
          // let fileUrl = "";
          // fileUrl = this.base64_url[0];
          // if(this.file_nums != ''){
          //   imgUrl = this.file_nums[0].url;
          // }else{
          //   let tmp = this.filesNums[0].url + ',' +this.filesNums[1].url
          //   imgUrl = tmp
          // }
          if (data.img_url != "") {
          let tmps = data.img_url.split(",").reverse()
          for(var i = 0;i<tmps.length;i++){
            this.fileLists.push({ url: tmps[i]});
            // this.base64_url.push(data.img_url);
          }
            
            
          }
          if (data.file_url != "") {
            this.fileList.push(data.file_url );
            this.base64_url.push(data.file_url);
          }
        }
      }
    },
    // 指派人员
    show_depart_list_assign() {
      let corpId = localStorage.getItem("custid");
      let appId = localStorage.getItem("appId");
      let _this = this;
      dd.biz.contact.complexPicker({
        title: "指派人员", //标题
        corpId: corpId, //企业的corpId
        multiple: true, //是否多选
        limitTips: "最多选择20人", //超过限定人数返回提示
        maxUsers: 20, //最大可选人数
        pickedUsers: [], //已选用户
        pickedDepartments: [], //已选部门
        disabledUsers: [], //不可选用户
        disabledDepartments: [], //不可选部门
        requiredUsers: [], //必选用户（不可取消选中状态）
        requiredDepartments: [], //必选部门（不可取消选中状态）
        appId: appId, //微应用的Id
        permissionType: "GLOBAL", //选人权限，目前只有GLOBAL这个参数
        responseUserOnly: true, //返回人，或者返回人和部门
        startWithDepartmentId: 0, // 0表示从企业最上层开始
        onSuccess: function(result) {
          let list_string = result.users;
          _this.assign_name =
            result.users[0].name + "等" + result.selectedCount + "人";
          let userList_string = "";
          for (let f = 0; f < list_string.length; f++) {
            userList_string += `${list_string[f].emplId},`;
          }
          _this.appointees_str = userList_string;
        },
        onFail: function(err) {}
      });
    },
    // 删除附件
    async beforDelete(file) {
      let tmp = this.base64_url;
      let arrTmp = this.fileList;
      let base64_name = "";
      if (arrTmp.length != 0 && this.$route.query.type == 6) {
        for (let j = 0; j < arrTmp.length; ++j) {
          if(arrTmp[j] == file){
          arrTmp.splice(j, 1);
          tmp.splice(j, 1);
          this.file_num.splice(j, 1)
        }
          if (file.url!=undefined&&file.url == arrTmp[j].url) {
            this.file_num.splice(j, 1)
            arrTmp.splice(j, 1);
            tmp.splice(j, 1);
          }
        }
        return;
      }
      for (let i = 0; i < tmp.length; ++i) {
        if(tmp[i] == file){  
          base64_name = tmp[i];
          arrTmp.splice(i, 1);
          tmp.splice(i, 1);
          this.file_num.splice(i, 1)
        }
       
        if (file.url!=undefined&&tmp[i] == file.url) {
          base64_name = tmp[i];
          arrTmp.splice(i, 1);
          tmp.splice(i, 1);
          this.file_num.splice(i, 1)
          
        }
      }
      let obj_name = {
        url: base64_name
      };
      // console.log(this.base64_url);
      // if (this.base64_url.length != 0) {
      var qs = require("qs");
      var instance = axios.create({
        headers: { "content-type": "application/x-www-form-urlencoded" }
      });
      const res = await instance.post(
        "https://upperinterface.changyuelife.com/dingAPI/deleteImage",
        qs.stringify(obj_name)
      );
      if (res.data.code != "0000") {
        this.$toast(res.data.message);
      }
    },
    // 删除图片
    async befor_Delete(file) {
      let tmp = this.fileLists;
      for (let i = 0; i < tmp.length+1; i++) {
        if (tmp[i].url === file.url) {
          tmp.splice(i, 1);
          this.fileLists.splice(i,1)
          this.filesNums.splice(i,1);
          this.file_nums.splice(i,1)
          let obj_name;
          let corpId = localStorage.getItem("custid");
          obj_name = {
            corpId: corpId,
            url: file.url
          };
          var qs = require("qs");
          var instance = axios.create({
            headers: { "content-type": "application/x-www-form-urlencoded" }
          });
          const res = await instance.post(
            "https://upperinterface.changyuelife.com/dingAPI/deleteImage",
            qs.stringify(obj_name)
          );
          if (res.data.code != "0000") {
            this.$toast(res.data.message);
          }
          return false
        }
      }
    },
    // 上传图片
    async afterRead(file) {
      this.isShowloading = true;
      let corpId = localStorage.getItem("custid");
      var qs = require("qs");
      var instance = axios.create({
        headers: { "content-type": "application/x-www-form-urlencoded" }
      });
      let _this = this;
      if (file.length > 1) {
        this.fileLists = [];
        let q = 0;
        for (let i = 0; i < file.length; ++i) {
          let obj_name = {
            corpId: corpId,
            base64: file[i].content
          };
          await instance
            .post(
              "https://upperinterface.changyuelife.com/dingAPI/upload",
              qs.stringify(obj_name)
            )
            .then(res => {
              if (res.data.code == "0000") {
                q++;
                _this.filesNums.push({ url: res.data.url });
              } else {
                _this.$toast("上传图片失败");
              }
            });
        }
        if (this.file_nums.length > 1) {
          this.fileLists = this.filesNums.concat(this.file_nums);
        } else {
          this.fileLists = this.filesNums;
        }
        if (this.is_loading_name == q) {
          this.isShowloading = false;
        }
      } else {
        this.fileLists = [];
        let obj_name = {
          corpId: corpId,
          base64: file.content
        };
        await instance
          .post(
            "https://upperinterface.changyuelife.com/dingAPI/upload",
            qs.stringify(obj_name)
          )
          .then(res => {
            if (res.data.code == "0000") {
              // Toast.success("图片上传成功");
              _this.isShowloading = false;
              _this.file_nums.push({ url: res.data.url });
              _this.fileLists = _this.file_nums;
            } else {
              _this.$toast("上传图片失败");
            }
          });
        if (this.filesNums.length > 1) {
          this.fileLists = this.filesNums.concat(this.file_nums);
        }
      }
    },
     // 图片校验
    before_Read(file) {
      if (file.size > 5 * 1024 * 1024) {
        Toast("上传文件大小不得超过3M");
        return false;
      }
      if (file.length > 1) {
        this.is_loading_name = file.length;
        for (let i = 0; i < file.length; i++) {
          if (file[i].size > 5 * 1024 * 1024) {
            this.$toast("上传文件大小不得超过3M");
            return false;
          }
        }
      }
      return true;
    },
    // 上传附件
    async after_read(file) {
      this.isShowloading = true;
      let corpId = localStorage.getItem("custid");
      this.fileList = [];
      var formData = new FormData();  
      let _this = this;
      console.log(file)
        formData.append("fileName", file.file);
        formData.append("corpId", corpId);
        // formData.append('enctype',"multipart/form-data")
        await axios
          .post(
            // "http://organization.changyuelife.com/dingAPI/uploadFile",
            "https://upperinterface.changyuelife.com/dingAPI/uploadFile",
            formData,
            { headers: { "Content-Type": "multipart/form-data" } }
          )
          .then(res => {
            if (res.data.code == "0000") {
              this.isShowloading = false;
              _this.base64_url.push(res.data.url);
               if (
              res.data.url.split(".").pop() == "png" ||
              res.data.url.split(".").pop() == "jpeg" ||
              res.data.url.split(".").pop() == "jpg"
            ) {
              _this.file_num.push({ url: res.data.url });
            } else {
              _this.file_num.push(res.data.url);
            }
            _this.fileList = _this.file_num;
            } else {
              _this.$toast("上传附件失败");
            }
          })
          .catch(function(err) {});
      // }
    },
    // // 附件校验
    beforeRead(file) {
      // if (this.fileList.length != 0) {
      //   for (let i = 0; i < this.fileList.length; i++) {
      //     if (
      //       this.fileList[i].url!=undefined
      //     ) {
            if (
              file.type == "image/png" ||
              file.type == "image/jpeg" ||
              file.type == "image/jpg"
            ) {
              this.$toast("不能上传类型相同的文件");
              return;
            }
        //   } else {
        //     if (
        //       this.fileList[i].split(".").pop() == file.name.split(".").pop()
        //     ) {
        //       this.$toast("不能上传类型相同的文件");
        //       return;
        //     }
        //   }
        // }
      // }
      if (file.size > 1 * 1024 * 1024) {
        this.$toast("上传文件大小不得超过1M");
        return false;
      }
      return true;
    },
    // 提交
    async show_sub() {
      // console.log(this.receiveNumber);
      if (this.event == "") {
        Toast("请选择申请事件");
        return;
      }
      if (this.taskTitle == "") {
        Toast("请选填写任务标题");
        return;
      }
      if (this.isRecruit_id == 2 && this.receiveNumber == "") {
        Toast("请选填写领取人数");
        return;
      }
      if(this.appointees_str=='' && this.isRecruit_id == 1){
        Toast("请选择指派人员");
        return;
      }
      if(this.start_id==0){
        Toast("请选择审核人");
        return;
      }
      if(this.end_id==0){
        Toast("请选择验收人");
        return;
      }
      let corpId = localStorage.getItem("custid");
      // let corpId = this.$utils.getUrlKey("custid");
      let userId = localStorage.getItem("userId");
      if (this.isRecruit_id == 0) {
        if (this.receive == "") {
          this.$toast("请填写领取" + this.D_name);
          return;
        }
        if (this.receiveScoreC == "" && this.is_c == 1) {
          this.$toast("请填写领取" + this.C_name);
          return;
        }
      }
      if (this.show_all == "默认全部") {
        this.show_str = 0;
      }
      if (this.isRecruit_id == 1) {
        this.get_time = "";
      } else {
        this.get_time = this.get_time;
      }
      
      let imgUrl = "";
      let fileUrl = "";
      
      if(this.fileLists.length == 2){
        let tmp = this.fileLists[0].url + ',' +this.fileLists[1].url
        imgUrl = tmp
      }else if(this.fileLists.length == 1){
        imgUrl = this.fileLists[0].url;
      }else{
        imgUrl = ""
      }
      if(this.base64_url != ''){
        fileUrl = this.base64_url[0];
      }
      let obj_name = {
        corpId: corpId,
        userId: userId,
        eventName: this.event,
        taskTile: this.taskTitle,
        isRecruit: this.isRecruit_id,
        desc: this.message,
        checkUser: this.end_id,
        approvalUser: this.start_id,
        receiveUpTo: this.get_time,
        startTime: this.get_time_start,
        endTime: this.get_time_end,
        isOpenC: this.is_c,
        isSubTask: this.isSubTask,
        finishScoringD: this.complete,
        overdueScoreD: this.deduction,
        receiveScoreD: this.receive,
        receiveScoreC: this.receiveScoreC,
        finishScoringC: this.finishScoringC,
        overdueScoreC: this.overdueScoreC,
        overdueDays: this.beOverdue,
        SubTaskData: this.children_list,
        range: this.show_str,
        appointees: this.appointees_str,
        receive_number: this.receiveNumber,
        fileUrl: fileUrl,
        imgUrl: imgUrl
      };
      this.sub_num = this.sub_num + 1;
      if (this.sub_num > 1) {
        Toast("请勿重复提交");
        return;
      }
      Toast.loading({
        message: "任务提交中",
        forbidClick: true,
        loadingType: "spinner"
      });
      var qs = require("qs");
      var instance = axios.create({
        headers: { "content-type": "application/x-www-form-urlencoded" }
      });
      let _this = this;
      await instance
        .post("yuepoints/releaseTask", qs.stringify(obj_name))
        .then(function(res) {
          const { errcode, errmsg } = res.data;
          if (errcode == "0000") {
            Toast.success("提交成功");
            _this.sub_num = 0;
            // _this.$router.replace("/home");
            _this.$router.push({
              //核心语句
              path: "/home", //跳转的路径
              query: {
                //路由传参时push和query搭配使用 ，作用时传递参数
                active: 2
              }
            });
          } else {
            _this.sub_num = 0;
            Toast(errmsg);
          }
        });
    },
    // 子任务时间开启
    timeShow_start(it, p) {
      this.show_children_time = true;
      this.public_time_start = p;
      this.time_isshow = 1;
    },
    // 子任务关闭时间
    timeShow_end(it, p) {
      this.show_children_time = true;
      this.public_time_end = p;
      this.time_isshow = 2;
    },
    // c分是否开启
    show_C() {
      if (this.checked == true) {
        this.is_c = 1;
      } else {
        this.receiveScoreC = "";
        this.finishScoringC = "";
        this.overdueScoreC = "";
        this.is_c = 0;
      }
    },
    // 领取时间
    show_time_one(i) {
      this.time_one = true;
      this.num_time = i;
    },
    // 开始时间
    show_time_two(i) {
      this.time_one = true;
      this.num_time = i;
    },
    // 结束时间
    show_time_three(i) {
      this.time_one = true;
      this.num_time = i;
    },
    children_time_one(time) {
      const d = new Date(time);
      let yy = d.getFullYear();
      let mm = this.p(d.getMonth() + 1);
      let dd = this.p(d.getDate());
      let hh = this.p(d.getHours());
      let mf = this.p(d.getMinutes());
      const resDate = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf;
      let arr = this.children_list;
      for (let i = 0; i < arr.length; i++) {
        if (this.public_time_start == i + 1 && this.time_isshow == 1) {
          arr[i].startTime = resDate;
        }
        if (this.public_time_end == i + 1 && this.time_isshow == 2) {
          arr[i].endTime = resDate;
        }
      }
      this.show_children_time = false;
    },
    // 时间筛选
    getTime_one(time) {
      const d = new Date(time);
      let yy = d.getFullYear();
      let mm = this.p(d.getMonth() + 1);
      let dd = this.p(d.getDate());
      let hh = this.p(d.getHours());
      let mf = this.p(d.getMinutes());
      const resDate = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf;
      if (this.num_time == 1) {
        this.get_time = resDate;
      }
      if (this.num_time == 2) {
        this.get_time_start = resDate;
      }
      if (this.num_time == 3) {
        this.get_time_end = resDate;
      }

      this.time_one = false;
    },
    p(s) {
      return s < 10 ? "0" + s : s;
    },
    // 发布范围
    show_Release_All() {
      let corpId = localStorage.getItem("custid");
      let appId = localStorage.getItem("appId");
      let depart_str = "";
      let _this = this;
      dd.biz.contact.departmentsPicker({
        title: "招募范围", //标题
        corpId: corpId, //企业的corpId
        multiple: true, //是否多选
        // limitTips: "最多选择20人", //超过限定人数返回提示
        maxDepartments: 100,
        pickedDepartments: [], //已选部门
        disabledDepartments: [], //不可选部门
        requiredDepartments: [], //必选部门（不可取消选中状态）
        appId: appId, //微应用的Id
        permissionType: "GLOBAL", //选人权限，目前只有GLOBAL这个参数
        responseUserOnly: true, //返回人，或者返回人和部门
        startWithDepartmentId: 0, // 0表示从企业最上层开始
        onSuccess: function(result) {
          if (result.departments.length == 0) {
            _this.show_all = "默认全部";
          } else {
            _this.show_all = "已选择" + result.departmentsCount + "个部门";
            for (let i = 0; i < result.departments.length; i++) {
              depart_str += `${result.departments[i].id},`;
            }
          }
          _this.show_str = depart_str;
        },
        onFail: function(err) {}
      });
    },
    // 验收人员
    async show_department_end() {
      let corpId = localStorage.getItem("custid");
      let appId = localStorage.getItem("appId");
      let _this = this;
      dd.biz.contact.complexPicker({
        title: "验收人", //标题
        corpId: corpId, //企业的corpId
        multiple: false, //是否多选
        limitTips: "只能选择一人", //超过限定人数返回提示
        maxUsers: 1, //最大可选人数
        pickedUsers: [], //已选用户
        pickedDepartments: [], //已选部门
        disabledUsers: [], //不可选用户
        disabledDepartments: [], //不可选部门
        requiredUsers: [], //必选用户（不可取消选中状态）
        requiredDepartments: [], //必选部门（不可取消选中状态）
        appId: appId, //微应用的Id
        permissionType: "GLOBAL", //选人权限，目前只有GLOBAL这个参数
        responseUserOnly: true, //返回人，或者返回人和部门
        startWithDepartmentId: 0, // 0表示从企业最上层开始
        onSuccess: function(result) {
          _this.end_id = result.users[0].emplId;
          _this.end_name = result.users[0].name;
        },
        onFail: function(err) {}
      });
    },
    // 任务类型
    show_isRecruit_id(i) {
      if (i == 0) {
        this.showMore = false;
        this.isRecruit = "招募";
        this.release_scope = true;
        this.Children_start = true;
        this.assign = false;
      } else if (i == 1) {
        this.showMore = false;
        this.release_scope = false;
        this.Children_start = false;
        this.assign = true;
        this.isRecruit = "指派";
      } else if (i == 2) {
        this.showMore = true;
        this.release_scope = true;
        this.Children_start = false;
        this.assign = false;
        this.isRecruit = "多人";
      }
      this.isRecruit_id = i;
      this.type = false;
    },
    //审核人
    async showPersonnel_start() {
      let corpId = localStorage.getItem("custid");
      let appId = localStorage.getItem("appId");
      let userId = localStorage.getItem("userId");
      let _this = this;
      const res = await this.$http.get(
        `yuepoints/getReviewer?corpId=${corpId}&userId=${userId}&type=1`
      );
      this.userlist = res.data.data.first;
      let users = [];
      for (var i = 0; i < this.userlist.length; i++) {
        users.push(this.userlist[i].dd_id);
      }
      dd.biz.customContact.choose({
        title: "审核人", //标题
        users: users, //一组员工userid
        corpId: corpId, //加密的企业 ID，
        isShowCompanyName: true, //true|false，默认为 false
        // disabledUsers: ["78308"], //不能选的人
        onSuccess: function(data) {
          _this.start_name = data[0].name;
          _this.start_id = data[0].emplId;
        },
        onFail: function(err) {}
      });
    },
    // 事件点击
    show_title_event(name) {
      this.Choice = false;
      this.event = name;
      localStorage.setItem("eventname",name);
      
    },
    async getEvent() {
      let corpId = localStorage.getItem("custid");
      const res = await this.$http.get(
        `/yuepoints/Event?corpId=${corpId}&type=0`
      );
      this.list = res.data.data;
    },
    // 添加子任务
    showChlid: function() {
      this.isSubTask = 1;
      this.children_list.push({
        taskTile: "",
        startTime: "开始时间",
        endTime: "结束时间",
        finishScoringD: "",
        finishScoringC: "",
        overdueScoreD: "",
        overdueScoreC: "",
        overdueDays: "",
        isShow: true
      });
      this.show = false;
      this.children_id = 1;
    },
    // 关闭子任务
    receiveShow: function(it, i) {
      this.children_list.splice(i - 1, 1);
      it.isShow = !it.isShow;
      if (i == 1) {
        this.show = true;
        this.isSubTask = 0;
      }
      this.children_id = 0;
    },
    getDay(day) {
      var today = new Date();
      var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
      today.setTime(targetday_milliseconds); //注意，这行是关键代码
      var tYear = today.getFullYear();
      var tMonth = today.getMonth();
      var tDate = today.getDate();
      let hh = today.getHours();
      let mf = "";
      if (Number(day) == 0) {
        mf = today.getMinutes() + 10;
        if (mf >= 60) {
          mf = mf - 60;
          hh = hh + 1;
        }
      } else {
        mf = today.getMinutes();
      }

      tMonth = this.doHandleMonth(tMonth + 1);
      tDate = this.doHandleMonth(tDate);
      hh = this.doHandleMonth(hh);
      mf = this.doHandleMonth(mf);
      return tYear + "-" + tMonth + "-" + tDate + " " + hh + ":" + mf;
    },
    doHandleMonth(month) {
      var m = month;
      if (month.toString().length == 1) {
        m = "0" + month;
      }
      return m;
    }
  }
};
</script>

<style lang="less" scoped>
.box {
  padding-bottom: 15px;
  font-size: 14px;
  .wrapper { 
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  // /deep/.van-field__label{
  //   width: 101px;
  // }
  /deep/ .van-field__control:disabled {
    color: #323233;
  }
  .childer_list {
    /deep/ .van-field__body {
      margin-left: 29px;
    }
  }
  .hidden {
    pointer-events: none;
    color: silver;
  }
  .show {
    pointer-events: auto;
  }
  .department_list {
    font-size: 14px;
    color: #1989fa;
    padding-left: 5px;
    position: absolute;
    top: 12px;
    right: 12px;
  }
  .personnel_text {
    display: inline-block;
    width: 42px;
    height: 42px;
    border-radius: 50%;
    background: #59d1ff;
    font-size: 14px;
    line-height: 42px;
    color: #fff;
  }
  .personnel_title {
    position: relative;
    bottom: 0px;
    left: 10px;
  }
  /deep/ .van-field__body {
    margin-left: 29px;
  }
  .active /deep/ .van-field__control {
    width: 90px;
  }
  .receive_C {
    position: absolute;
    right: 25vw;
    top: 50%;
    width: 55px;
    transform: translate(-50%, -50%);
  }
  .public {
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    box-sizing: border-box;
    width: 100%;
    padding: 10px 16px;
    overflow: hidden;
    color: #323233;
    font-size: 14px;
    line-height: 24px;
    background-color: #fff;
    .left_wrap{
      flex: none;
      box-sizing: border-box;
      width: 90px;
      text-align:left;
      .Left{
        margin-left:17px;
        color: #323233;
        font-size: 14px;
        line-height: 24px
        
      }
    }
    .right_wrap{
      flex: 1 0 auto;
      margin-left:29px;
      box-sizing: border-box;
      text-align:left;
      width: 90px;
      .Right{
        color: #323233;
        font-size: 14px;
        line-height: 24px
      }
    }           

  }
  .left {
    float: left;
  }
  .right {
    float: right;
  }
}
.clearfix::after {
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  zoom: 1;
}
input::-webkit-input-placeholder {
  color: rgb(168, 168, 168);
}
input::-moz-input-placeholder {
  color: #cbcccd;
}
input::-ms-input-placeholder {
  color: #cbcccd;
}
</style>
